﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IUI;
using Data;
using System.Data;

namespace BL
{
    public class ManagePlaylistController : BaseController<IManagePlaylist>
    {
        public ManagePlaylistController(IManagePlaylist page) : base(page) 
        {
            WCF_Client.Instance.Connect();
        }
      
        public override void InitPageEvents()
        {
            _page.Shown += PageShown;
            _page.Click_Remove += RemoveSong;
            _page.Click_Add += AddSong;
        }

        void PageShown(object sender, EventArgs e)
        {
            _page.FillLists(NotInListSongs());
        }

        DataTable NotInListSongs()
        {
            DataTable tmp = WCF_Client.Instance.GetTable(Song.TableName);

            List<String> list_to_delete = new List<String>();

            foreach (var song in _page.Playlist.Songs)
            {
                list_to_delete.Add(((Song)song).ID.ToString());
            }
            
            DataColumn[] pk = { tmp.Columns["id"] } ;
            tmp.PrimaryKey = pk;

            foreach (var id in list_to_delete)
            {
                tmp.Rows.Find((String) id).Delete();
            }
            
            tmp.AcceptChanges();

            return tmp;
        }

        void RemoveSong(object sender, EventArgs e)
        {
            Song tmp_song = _page.SongToRemove;

            WCF_Client.Instance.DeletePlaylistConnector(PlaylistConnector.GetBySongAndPlaylist(tmp_song, _page.Playlist));

            PlaylistConnector.GetBySongAndPlaylist(tmp_song, _page.Playlist).Delete();

            _page.FillLists(NotInListSongs());
        }

        void AddSong(object sender, EventArgs e)
        {
            Guid g = _page.IdSongToAdd;
            if (g != Guid.Empty)
            {
                Song s = WCF_Client.Instance.CreateSong(g);
                PlaylistConnector c = new PlaylistConnector(s, _page.Playlist);
                WCF_Client.Instance.SavePlaylistConnector(c);

                DataTable tmp = NotInListSongs();

                _page.FillLists(tmp);
            }
        }
    }
}
